import threading
import requests
import io
from PIL import Image


def capture_frames(
    source: str,
    cookies: dict,
):
    """从指定源捕获视频帧并定时保存到本地"""
    cookie = cookies.get("auth_token")
    # 处理HTTP/HTTPS图像源
    if str(source).startswith("http"):
        response = requests.get(source,
                                stream=True,
                                timeout=10,
                                verify=False,
                                cookies={"auth_token": cookie})

        if response.status_code == 200:
            # 处理MJPEG流
            if 'multipart' in response.headers.get(
                    'Content-Type', '') or 'mjpeg' in response.headers.get(
                        'Content-Type', ''):
                bytes_data = bytes()
                for chunk in response.iter_content(chunk_size=1024):
                    # 检查是否需要停止
                    bytes_data += chunk
                    a = bytes_data.find(b'\xff\xd8')  # JPEG开始
                    b = bytes_data.find(b'\xff\xd9')  # JPEG结束
                    if a != -1 and b != -1:
                        jpg = bytes_data[a:b + 2]
                        bytes_data = bytes_data[b + 2:]
                        try:
                            img = Image.open(io.BytesIO(jpg))
                        except Exception as e:
                            print(f"处理帧时出错: {e}")
                        img.save(f"test.jpg")


def login():
    """模拟登录操作"""
    # 这里可以添加登录逻辑
    url = "https://100.109.226.25/api/auth/login"
    session = requests.Session()
    payload = {"user": "admin", "passwd": "admin"}
    try:
        response = session.post(url, data=payload, verify=False, timeout=10)
        if response.status_code == 200:
            print(response.text)
            print("登录成功，获取cookie:", session.cookies.get_dict())
            return session.cookies.get_dict()
        print("登录失败")
    except Exception as e:
        print(f"登录请求异常: {e}")
    return None


if __name__ == "__main__":
    cookies = login()
    if cookies:
        # 启动帧捕获线程
        capture_thread = threading.Thread(
            target=capture_frames,
            args=("https://100.109.226.25/streamer/stream", cookies),
            daemon=True)
        capture_thread.start()
